package com.chen.auth.listener;

import cn.hutool.core.collection.CollUtil;
import com.chen.auth.event.LogoutSuccessEvent;
import com.chen.auth.handler.AuthenticationLogoutEventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 退出登录成功事件监听器
 * @Author C_Y_J
 * @create 2022/1/20 9:55
 **/
@Slf4j
@Component
public class AuthenticationLogoutEventListener implements ApplicationListener<LogoutSuccessEvent> {

    @Resource
    AuthenticationLogoutEventHandler authenticationLogoutEventHandler;

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(LogoutSuccessEvent event) {
        OAuth2Authentication authentication = (OAuth2Authentication) event.getSource();

        // 是认证用户 。从请求上下文中拿到请求属性
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();

        // 调用自定义业务实现
        authenticationLogoutEventHandler.handle(authentication, request, response);
    }

    private boolean isUserAuthentication(Authentication authentication) {
        return authentication.getPrincipal() instanceof UserDetails || CollUtil.isNotEmpty(authentication.getAuthorities());
    }
}
